<template>
  <div class="home" :class="{ is_login: type === 'login', is_forget: type === 'forget' }">
    <div class="home_content">
      <div class="home-top">
        <div class="title">
          <span v-if="type === 'login'">欢迎登录</span>
          <span v-if="type === 'forget'">忘记密码</span>
        </div>
      </div>
      <div class="form">
        <ul v-if="type === 'login'" :class="['login-type', loginType]">
          <li
            :class="['login-item', 'login-type-1', loginType === 'account' ? 'active' : '']"
            @click.stop="onLoginTypeChange('account')">
            账号登录
          </li>
          <li
            :class="['login-item', 'login-type-2', loginType === 'quick' ? 'active' : '']"
            @click.stop="onLoginTypeChange('quick')">
            验证码登录
          </li>
        </ul>
        <template v-if="type === 'login'">
          <QuickForm v-if="loginType === 'quick'" @login="onLogin"></QuickForm>
          <AccountForm v-else @login="onLogin" @show-forget="resetPassword"></AccountForm>
        </template>

        <van-form v-if="type === 'forget'" class="reset" validate-first ref="resetFormRef">
          <div class="form_list">
            <div class="form-label">手机号</div>
            <van-field
              v-model="resetForm.phoneNum"
              name="phoneNum"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请输入手机号' }]"
              maxlength="11" />
          </div>
          <div class="form_list">
            <div class="form-label">验证码</div>
            <van-field
              v-model="resetForm.phoneCode"
              name="phoneCode"
              placeholder="请输入验证码"
              :rules="rules.phoneCode"
              maxlength="6">
              <template #button>
                <div class="code" @click="sendCode">{{ codeBtnDisplay }}</div>
              </template>
            </van-field>
          </div>
          <div class="form_list">
            <div class="form-label">新密码</div>
            <van-field
              v-model="resetForm.newPwd"
              name="newPwd"
              placeholder="请设置新密码"
              :rules="rules.newPwd"></van-field>
          </div>
          <div class="form_list">
            <div class="form-label">确认密码</div>
            <van-field
              v-model="resetForm.repeatPwd"
              name="repeatPwd"
              placeholder="请确认新密码"
              :rules="rules.repeatPwd"></van-field>
          </div>
          <div class="btn-box">
            <div class="commit" @click="editPassWord">提交</div>
            <div class="back" @click="backLogin">返回登录</div>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
import { internalLogin, sendSignCode, updateLoginPassword } from '@api/api-public.js'
import { mapState } from 'vuex'
import { getBrowser, getResolvingPower, getDetectOS } from '@/common/utility.js'
import QuickForm from './components/QuickForm.vue'
import AccountForm from './components/AccountForm.vue'

export default {
  name: 'Login',
  components: { QuickForm, AccountForm },
  props: {},
  data() {
    const that = this
    return {
      title: 'i绩效',
      // 阿里云登录
      loginName: '',
      loginPassword: '',
      // 系统类型
      sysInfo: {
        // 浏览器类型
        browser: '',
        // 操作系统
        userOs: '',
        // 分辨率
        resolution: '',
        // 屏幕大小
        screenSize: '',
      },
      pswTypeShow: true,
      type: 'login', // 登录:login、忘记密码:forget
      resetForm: {
        phoneNum: '',
        phoneCode: '',
        newPwd: '',
        repeatPwd: '',
      },
      cutdownSec: 0,
      sendCodeStatus: 'init', // init, send, retry
      cutdownTimer: null,
      rules: {
        //验证规则
        phoneCode: [
          {
            pattern: /^\d{6}$/,
            message: '请输入有效的验证码',
          },
        ],
        newPwd: [
          {
            required: true,
            message: '请设置新密码',
          },
          {
            validator: val => {
              let pattern1 =
                /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/
              if (!pattern1.test(val)) {
                return false
              }
            },
            message: '密码长度8~16，包含数字、大小写字母、特殊字符中至少3种!',
          },
        ],
        repeatPwd: [
          {
            required: true,
            message: '请确认新密码',
          },
          {
            validator: val => {
              if (val !== that.resetForm.newPwd) {
                return false
              }
            },
            message: '与新密码不一致',
          },
        ],
      },
      isRemember: false,
      loginType: 'account',
    }
  },
  computed: {
    codeBtnDisplay() {
      if (this.sendCodeStatus === 'init') {
        return '获取验证码'
      } else if (this.sendCodeStatus === 'send') {
        return this.cutdownSec + ' 秒'
      }
      return '重新获取'
    },
  },
  created() {
    setTimeout(() => {
      if (window.flutter_inappwebview) {
        window.resUser = this.resUser
        window.flutter_inappwebview.callHandler('getUser', '')
      }
    }, 300)
  },
  mounted() {
    this.sysInfo = {
      // 浏览器类型
      browser: `${getBrowser().client.name}_${getBrowser().client.version}`,
      // 操作系统
      userOs: getDetectOS(),
      // 系统分辨率
      resolution: getResolvingPower().sysResolution,
      // 屏幕大小
      screenSize: getResolvingPower().sysScreen,
    }
  },
  watch: {},
  methods: {
    resUser(json) {
      // console.log('原生返回数据:', JSON.stringify(json))
      this.loginSuccess(json)
    },

    // 登录成功回调
    async loginSuccess(res) {
      if (res.platform) {
        localStorage.setItem('platform', res.platform)
      } else {
        localStorage.setItem('platform', this.sysInfo.userOs)
      }
      sessionStorage.setItem('userId', res.userId)
      sessionStorage.setItem('userName', res.userName)
      sessionStorage.setItem('token', res.token)
      sessionStorage.setItem('userInfo', JSON.stringify(res))
      // 本地免登陆验证
      localStorage.setItem('userId', res.userId)
      localStorage.setItem('token', res.token)
      localStorage.setItem('userInfo', JSON.stringify(res))
      localStorage.setItem('tenantId', res.tenantId)
      localStorage.setItem('user_remember', this.remember)
      localStorage.setItem('user_loginName', this.loginName)
      localStorage.setItem('user_loginPassword', window.btoa(this.loginPassword))
      localStorage.setItem('sysInfo', JSON.stringify(this.sysInfo))

      const expireTime = res.endTime || ''
      if (expireTime) {
        const expireDate = new Date(expireTime)
        let vipTimes = 0
        vipTimes = expireDate.getTime() - new Date(res.loginTime || new Date()).getTime()
        if (vipTimes < 0) {
          res.vipDays = 0
        } else {
          vipTimes = vipTimes / 1000
          res.vipDays = Math.ceil(vipTimes / 3600 / 24)
        }
      } else {
        res.vipDays = 0
      }
      this.$store.state.role.isAgainLogin = true
      this.$store.commit('role/setUserInfo', res)

      try {
        await this.$store.dispatch('role/getUserPermissions')
      } catch (err) {
      } finally {
        this.$router.push('/home')
        // if (res.isPwdSimple === 1) {
        //   this.$router.push('/password')
        // } else {
        //   this.$router.push('/home')
        // }
      }
    },
    resetPassword() {
      this.cutdownSec = 0
      this.sendCodeStatus = 'init'
      this.cutdownTimer = null
      this.resetForm = {
        phoneNum: '',
        phoneCode: '',
        newPwd: '',
        repeatPwd: '',
      }

      this.type = 'forget'
    },
    backLogin() {
      this.loginName = ''
      this.loginPassword = ''
      this.$refs.resetFormRef.resetValidation()
      this.type = 'login'
    },
    // 发送验证码
    sendCode() {
      if (this.sendCodeStatus === 'send') {
        return
      }
      this.$refs.resetFormRef
        .validate('phoneNum')
        .then(() => {
          const params = {
            oneParam: this.resetForm.phoneNum,
            check: '1',
            sendType: '1',
            tenantId: '',
          }
          sendSignCode(params).then(res => {
            if (res.status === 200) {
              this.startCutdown()
            }
          })
        })
        .catch(err => {
          console.log('err :>> ', err)
        })
    },
    // 验证码有效期开始计时
    startCutdown() {
      this.clearCutdownTimer()
      this.sendCodeStatus = 'send'
      this.cutdownSec = 60
      this.cutdownTimer = setInterval(() => {
        this.cutdownSec--
        if (this.cutdownSec <= 0) {
          this.clearCutdownTimer()
          this.sendCodeStatus = 'retry'
        }
      }, 1000)
    },
    // 清除计时器
    clearCutdownTimer() {
      if (this.cutdownTimer) {
        clearInterval(this.cutdownTimer)
      }
    },
    editPassWord() {
      this.$refs.resetFormRef
        .validate()
        .then(() => {
          updateLoginPassword({
            telephone: this.resetForm.phoneNum,
            smCode: this.resetForm.phoneCode,
            type: '2',
            tenantId: '',
            newPwd: this.resetForm.newPwd,
            repeatPwd: this.resetForm.repeatPwd,
          }).then(res => {
            if (res.status === 200) {
              this.$toast.success('修改密码成功')
              this.backLogin()
            }
          })
        })
        .catch(fail => {
          console.log('fail :>> ', fail)
          this.$toast.fail(fail[0].message)
        })
    },
    onLoginTypeChange(type) {
      this.loginType = type
    },
    onLogin(obj) {
      let params = {}
      if (this.loginType === 'account') {
        params = {
          loginName: obj.loginName || '',
          loginPassword: obj.loginPassword || '',
          smCode: '',
          loginType: '1',
        }
      } else {
        params = {
          loginName: obj.phone || '',
          loginPassword: '',
          smCode: obj.smCode || '',
          loginType: '2',
        }
      }
      internalLogin({
        appCode: 'jx-clivil-servant-assessment',
        currentUserId: '',
        platType: 1,
        ...this.sysInfo,
        ...params,
      }).then(res => {
        if (res.status == 200) {
          this.loginName = params.loginName
          this.loginPassword = params.loginPassword
          this.loginSuccess(res.data)
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100%;
  .home-top {
    position: absolute;
    top: 53px;
    left: 39px;
    .title {
      color: #000000;
      font-size: 25px;
    }
  }
  .home_content {
    width: 100%;
  }
  .form {
    width: 100%;
    padding: 0 39px;
    .login-type {
      width: 100%;
      max-width: 360px;
      margin: 0 auto;
      margin-bottom: 20px;
      font-size: 0;
      position: relative;
      text-align: center;
      .login-item {
        display: inline-block;
        cursor: pointer;
        color: #707070;
        font-weight: 400;
        vertical-align: top;
        font-size: 20px;
        height: 26px;
        line-height: 26px;
        &.login-type-1 {
          text-align: right;
          padding-right: 20px;
        }
        &.login-type-2 {
          text-align: left;
          padding-left: 20px;
        }
      }
      .login-item.active {
        color: #000;
      }
      &::after {
        display: block;
        content: '';
        height: 2px;
        bottom: -5px;
        position: absolute;
        background-color: #006ff2;
      }
      &.account::after {
        width: 80px;
        left: calc(50% - 110px);
        transition: left 0.3s;
      }
      &.quick::after {
        width: 100px;
        left: calc(50% + 10px);
        transition: left 0.3s;
      }
    }
    /deep/ .van-form {
      width: 100%;
      .form_list {
        width: 100%;
        border-bottom: 1px solid #dfdfdf;
        margin-bottom: 10px;
        padding-bottom: 5px;
        .form-label {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 10px;
        }
        .form-con {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .iconfont {
            font-size: 22px;
            color: #a8d2f7;
            &.psw {
              margin-right: 20px;
            }
          }
          .van-cell {
            height: 100%;
            font-size: 14px;
            background-color: transparent;
          }
        }
      }
      .form-use {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #004db6;
        .van-checkbox__icon--square {
          .van-icon-success {
            border-radius: 2px;
          }
        }
        .van-checkbox__label {
          color: #004db6;
        }
      }
    }
    .commit {
      margin-top: 30px;
      height: 45px;
      line-height: 45px;
      border-radius: 6px;
      background: #004db6;
      color: #ffffff;
      text-align: center;
      font-weight: bold;
    }
  }
}
.is_login {
  background-image: url('../../assets/images/login/bg_denglu.png');
  background-position: 0 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  .form {
    padding-top: 380px;
  }
}
.is_forget {
  .home-top {
    left: 25px;
  }
  .form {
    padding: 150px 25px 0;
  }
  .code {
    color: #004db6;
  }
  .commit {
    margin-top: 60px !important;
  }
  .back {
    margin-top: 15px;
    height: 45px;
    line-height: 45px;
    border-radius: 6px;
    background-color: rgba(0, 77, 182, 0.15);
    color: #004db6;
    text-align: center;
    font-weight: bold;
  }
}
</style>
